package org.douxiaoban.client.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.*;
import com.google.gdata.data.douban.Attribute;
import com.google.gdata.data.douban.Tag;
import com.mobclick.android.MobclickAgent;
import org.douxiaoban.client.R;
import org.douxiaoban.client.adapter.CollectionListAdapter;
import org.douxiaoban.client.api.CollectionRecord;
import org.douxiaoban.client.api.ReviewRecord;
import org.douxiaoban.client.api.SubjectRecord;
import org.douxiaoban.client.app.Assistant;
import org.douxiaoban.client.model.BundleSerializable;
import org.douxiaoban.client.model.TestsSerializable;
import org.douxiaoban.client.util.ThreadTool;
import org.douxiaoban.client.util.WorkspaceView;
import org.douxiaoban.client.widget.PopupRecommend;
import org.douxiaoban.client.widget.TitleStyle;

import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: huangzhongkun
 * Date: 11-6-8
 * Time: 下午11:47
 */
public class SearchResultActivity extends BaseActivity {

    private ThreadTool _thread;
    private String _type;
    private String _keyword;
    private int _startIndex = 1;
    private LayoutInflater _inflater;
    private ArrayList<SubjectRecord> subjectRecords = null;
    private ArrayList<Bitmap> _subject_bitmaps;
    private ArrayList<ImageView> _subject_imageview;

    //View
    private ScrollView _scrollview;
    private LinearLayout _progress_lay;
    private RelativeLayout _search_result_lay;
    private LinearLayout _search_content_lay;
    private Button _search_more_btn;
    private ImageView _search_type_img;
    private TextView _search_summary_text;
    private TitleStyle _title_style;
    private PopupRecommend _popup_recommend;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        _inflater = LayoutInflater.from(this);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.search_result);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);

        setupIntent();
        setupView();

        _popup_recommend = new PopupRecommend(this);
        _title_style = new TitleStyle(this);
        _title_style.initTitleStyle();
    }

    private void setupIntent(){
        Intent intent = getIntent();
        _keyword = intent.getStringExtra(Assistant.KEY_OF_KEYWORD);
        _type = intent.getStringExtra(Assistant.KEY_OF_TYPE);

        _thread = ThreadTool.instace(this);
        _thread.startThreadSearchSubject(_handler,_type,_keyword,_startIndex,10);
    }

    private void setupView(){
        _subject_bitmaps = new ArrayList<Bitmap>();
        _subject_imageview = new ArrayList<ImageView>();
        _scrollview = (ScrollView)this.findViewById(R.id.search_result_scroll_view);
        _progress_lay = (LinearLayout)this.findViewById(R.id.search_progress_lay);
        _search_result_lay = (RelativeLayout)this.findViewById(R.id.search_result_lay);
        _search_content_lay = (LinearLayout)this.findViewById(R.id.search_result_content_lay);
        _search_more_btn = (Button)this.findViewById(R.id.search_more_btn);
        _search_type_img = (ImageView)this.findViewById(R.id.search_type_image);
        _search_summary_text = (TextView)this.findViewById(R.id.search_summary_text);

        _search_more_btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                _search_more_btn.setText(getText(R.string.loading));
                _search_more_btn.setEnabled(false);
                _thread.startThreadSearchSubject(_handler,_type,_keyword,_startIndex,10);
            }
        });
    }

    private Handler _handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Assistant.FETCH_SEARCH_DONE:
                    Bundle bundle = msg.getData();
                    BundleSerializable bundleSerializable =
                            (BundleSerializable)bundle.getSerializable(Assistant.KEY_OF_SUBJECT);

                        subjectRecords = bundleSerializable.sjs;


                    _search_more_btn.setText(getString(R.string.search_more));

                    int totalResult = subjectRecords.get(0).totalResult;
                    if(totalResult<=10 || totalResult<=(subjectRecords.size()
                            +_subject_imageview.size()))
                    _search_more_btn.setVisibility(View.GONE);

                    updateView();
                    _startIndex = _startIndex +10;
                    break;
                case Assistant.FETCH_SEARCH_FAIL:
                    _popup_recommend.showToastWindow(0,getString(R.string.load_fail));
                    finish();
                    break;
                case Assistant.FETCH_REVIEW_AVATAR_DONE:
                    Bundle bundleAvatar = msg.getData();
                    BundleSerializable bsAvatar =  (BundleSerializable)
                            bundleAvatar.getSerializable(Assistant.KEY_OF_IMAGE);
                    updateImage(bsAvatar.reviewAvatars);
                    break;
            }
        }
    };

    private void updateImage(ArrayList<Bitmap> avatars){
        int i=0;
        for (Bitmap bitmap:avatars){
            _subject_bitmaps.add(bitmap);
        }

        for (ImageView imageView:_subject_imageview){
            if(_subject_bitmaps.get(i)!=null)
                imageView.setImageBitmap(_subject_bitmaps.get(i));
            i++;
        }
    }

    private void updateView(){
        _progress_lay.setVisibility(View.GONE);
        _search_result_lay.setVisibility(View.VISIBLE);


        String[] urls = new String[subjectRecords.size()];
        int i=0;
        for(SubjectRecord sr:subjectRecords){
            urls[i] = sr.icon_url;
            i++;
        }
        _search_summary_text.setText("\""+_keyword+"\"结果条数为"+subjectRecords.get(0).totalResult);
        _thread.startThreadFetchReviewAvatar(_handler,urls,this);

        for (SubjectRecord subjectRecord:subjectRecords){
            addCellView(subjectRecord);
        }

        if(_type.equals(Assistant.STATUS_MOVICE)){
            _search_type_img.setImageBitmap(BitmapFactory.
                    decodeResource(getResources(),R.drawable.search_movie_img));
        }else if(_type.equals(Assistant.STATUS_MUSIC)){
            _search_type_img.setImageBitmap(BitmapFactory.
                    decodeResource(getResources(),R.drawable.search_music_img));
        }else{
            _search_type_img.setImageBitmap(BitmapFactory.
                    decodeResource(getResources(),R.drawable.search_book_img));
        }
    }

    private void addCellView(SubjectRecord subjectRecord){
        View cellview = _inflater.inflate(R.layout.collections_item,null);
        TextView titleView = (TextView)cellview.findViewById(R.id.wish_read_book_title);
        RatingBar ratingBar = (RatingBar)cellview.findViewById(R.id.wish_read_book_rating);
        TextView updateView = (TextView)cellview.findViewById(R.id.wish_read_book_updatedate);
        TextView attributeView = (TextView)cellview.findViewById(R.id.wish_read_book_attribute);
        TextView tagVIEW = (TextView)cellview.findViewById(R.id.wish_read_book_tags);
        ImageView iconImageView = (ImageView)cellview.findViewById(R.id.wish_read_book_icon);
        cellview.findViewById(R.id.wish_read_book_summary).setVisibility(View.GONE);
        cellview.findViewById(R.id.wish_read_book_tags).setVisibility(View.GONE);
        cellview.findViewById(R.id.item_driver_image).setVisibility(View.VISIBLE);

        _subject_imageview.add(iconImageView);
        String attribute="";
        String tag = "";

        if(subjectRecord.attributes!=null&& subjectRecord.attributes.size() >0){
            int i = 0;
            for(Attribute item:subjectRecord.attributes){
                int t = item.getContent().indexOf("http");
                if(item.getContent().indexOf("http")>=0)
                    continue;

                if(i>1)
                  attribute += "/"+item.getContent();
                  i++;
            }
        }

        if(attribute.length()>200)
            attribute = attribute.substring(0,110);
        attribute += "...<a href=\"www\">查看全部</a>";

        if(subjectRecord.tags.size() != 0){
               for(Tag item:subjectRecord.tags){
                   tag += item.getName()+" ";
               }
        }

        titleView.setText(subjectRecord.title);
        ratingBar.setRating(subjectRecord.rating_average/2);
        updateView.setText(subjectRecord.update_date);

        if(attribute!=null)
            attributeView.setText(Html.fromHtml(attribute));

        if(tag!=null)
            tagVIEW.setText(tag);

        attributeView.setMovementMethod(LinkMovementMethod.getInstance());
        CharSequence text =attributeView.getText();

        if(text instanceof Spannable){
            //在评论尾端加入支持点击事件的文本
            Spannable sp = (Spannable)attributeView.getText();
            URLSpan[] urls = sp.getSpans(0, text.length(), URLSpan.class);
            SpannableStringBuilder style = new SpannableStringBuilder(text);
            style.clearSpans();

            for(URLSpan s:urls){
                ClickURLSpan myURLSpan =new ClickURLSpan(_type,
                        subjectRecord);
                style.setSpan(myURLSpan,sp.getSpanStart(s),sp.getSpanEnd(s),
                        Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            }
            attributeView.setText(style);
        }


        _search_content_lay.addView(cellview);

    }

     /**
     * 自定义的USLSPan子类，用来扑获超链接文本的点击事件
     */
    private  class ClickURLSpan extends ClickableSpan {
        private String str;
        private SubjectRecord subjectRecord;

        public ClickURLSpan(String str,SubjectRecord reviewRecord){
            this.str = str;
            this.subjectRecord = reviewRecord;
         }

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(SearchResultActivity.this,
                                    CollectionSubjectActivity.class);

            intent.putExtra(Assistant.KEY_OF_INTENT_ID,subjectRecord.id);
            intent.putExtra(Assistant.KEY_OF_INTENT_CATEGORY,str);
            startActivity(intent);
        }
    }

      @Override
    protected void onResume() {
        MobclickAgent.onResume(this);
        super.onResume();    //Super Method super.onResume();
    }

    @Override
    protected void onPause() {
        MobclickAgent.onPause(this);
        super.onPause();    //Super Method super.onPause();
    }
}